/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.api.runtime.process.spring;

import com.je.bpm.core.model.FlowElement;
import com.je.bpm.engine.ActivitiException;
import com.je.bpm.engine.impl.bpmn.behavior.MappingExecutionContext;
import com.je.bpm.engine.impl.bpmn.behavior.VariablesCalculator;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.persistence.entity.ExecutionEntity;
import com.je.bpm.engine.impl.util.ProcessDefinitionUtil;
import com.je.bpm.engine.impl.util.ProcessInstanceHelper;
import com.je.bpm.engine.repository.ProcessDefinition;
import com.je.bpm.spring.process.ProcessExtensionService;
import com.je.bpm.spring.process.model.Extension;
import com.je.bpm.spring.process.model.VariableDefinition;
import com.je.bpm.spring.process.variable.VariableParsingService;
import com.je.bpm.spring.process.variable.VariableValidationService;

import java.util.*;

import static java.util.Collections.emptyMap;

public class ProcessVariablesInitiator extends ProcessInstanceHelper {

    private ProcessExtensionService processExtensionService;

    private final VariableParsingService variableParsingService;

    private final VariableValidationService variableValidationService;

    private VariablesCalculator variablesCalculator;

    public ProcessVariablesInitiator(ProcessExtensionService processExtensionService, VariableParsingService variableParsingService, VariableValidationService variableValidationService, VariablesCalculator variablesCalculator) {
        this.processExtensionService = processExtensionService;
        this.variableParsingService = variableParsingService;
        this.variableValidationService = variableValidationService;
        this.variablesCalculator = variablesCalculator;
    }

    public Map<String, Object> calculateVariablesFromExtensionFile(ProcessDefinition processDefinition, Map<String, Object> variables) {
        Map<String, Object> processedVariables = new HashMap<>();
        if (processExtensionService.hasExtensionsFor(processDefinition)) {
            Extension processExtension = processExtensionService.getExtensionsFor(processDefinition);
            Map<String, VariableDefinition> variableDefinitionMap = processExtension.getProperties();
            processedVariables = processVariables(variables, variableDefinitionMap);
            Set<String> missingRequiredVars = checkRequiredVariables(processedVariables, variableDefinitionMap);
            if (!missingRequiredVars.isEmpty()) {
                throw new ActivitiException("Can't start process '" + processDefinition.getKey() + "' without required variables - " + String.join(", ", missingRequiredVars));
            }
            Set<String> varsWithMismatchedTypes = validateVariablesAgainstDefinitions(processedVariables, variableDefinitionMap);
            if (!varsWithMismatchedTypes.isEmpty()) {
                throw new ActivitiException("Can't start process '" + processDefinition.getKey() + "' as variables fail type validation - " + String.join(", ", varsWithMismatchedTypes));
            }
        }

        return processedVariables;
    }

    public Map<String, Object> calculateOutputVariables(Map<String, Object> variables, ProcessDefinition processDefinition, FlowElement initialFlowElement) {
        Map<String, Object> processVariables = variables;
        if (processExtensionService.hasExtensionsFor(processDefinition)) {
            Map<String, Object> calculateOutPutVariables = variablesCalculator.calculateOutPutVariables(MappingExecutionContext.buildMappingExecutionContext(
                            processDefinition.getId(),
                            initialFlowElement.getId()),
                    variables);
            if (!calculateOutPutVariables.isEmpty()) {
                processVariables = calculateOutPutVariables;
            }

            processVariables = calculateVariablesFromExtensionFile(processDefinition,
                    processVariables);
        }
        return processVariables;
    }

    private Map<String, Object> processVariables(Map<String, Object> variables, Map<String, VariableDefinition> variableDefinitionMap) {
        Map<String, Object> newVarsMap = new HashMap<>(Optional.ofNullable(variables).orElse(emptyMap()));
        variableDefinitionMap.forEach((k, v) -> {
            if (!newVarsMap.containsKey(v.getName()) && v.getValue() != null) {
                newVarsMap.put(v.getName(), createDefaultVariableValue(v));
            }
        });
        return newVarsMap;
    }

    private Object createDefaultVariableValue(VariableDefinition variableDefinition) {
        // take a default from the variable definition in the proc extensions
        return variableParsingService.parse(variableDefinition);
    }

    private Set<String> checkRequiredVariables(Map<String, Object> variables, Map<String, VariableDefinition> variableDefinitionMap) {
        Set<String> missingRequiredVars = new HashSet<>();
        variableDefinitionMap.forEach((k, v) -> {
            if (!variables.containsKey(v.getName()) && v.isRequired()) {
                missingRequiredVars.add(v.getName());
            }
        });
        return missingRequiredVars;
    }

    private Set<String> validateVariablesAgainstDefinitions(Map<String, Object> variables, Map<String, VariableDefinition> variableDefinitionMap) {
        Set<String> mismatchedVars = new HashSet<>();
        variableDefinitionMap.forEach((k, v) -> {
            //if we have definition for this variable then validate it
            if (variables.containsKey(v.getName())) {
                if (!variableValidationService.validate(variables.get(v.getName()), v)) {
                    mismatchedVars.add(v.getName());
                }
            }
        });
        return mismatchedVars;
    }

    @Override
    public void startProcessInstance(ExecutionEntity processInstance, CommandContext commandContext, Map<String, Object> variables, FlowElement initialFlowElement, Map<String, Object> transientVariables) {
        ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(processInstance.getProcessDefinitionId());
        Map<String, Object> calculatedVariables = calculateOutputVariables(variables, processDefinition, initialFlowElement);
        super.startProcessInstance(processInstance, commandContext, calculatedVariables, initialFlowElement, transientVariables);
    }
}
